/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var mergeKLists = function (lists) {
  if (lists.length === 0) return null
  const mergeNodeList = arr => {
    const listObj = {}
    arr.forEach(item => {
      if (item) {
        // if (listObj[item.val]) {
        //   listObj[item.val].next = item
        // }
        listObj[item.val] = item
      }
    })
    const maxKey = Math.min(...Object.keys(listObj))
    const index = arr.indexOf(listObj[maxKey])
    if (index === -1) {
      return null
    }
    const nextData = arr[index].next
    nextData ? arr.splice(index, 1, nextData) : arr.splice(index, 1)
    listObj[maxKey].next = arr.length > 0 ? mergeNodeList(arr) : null
    return listObj[maxKey]
  }

  return mergeNodeList(lists)
}
const createListNode = arr => {
  function ListNode(val, next) {
    this.val = val === undefined ? 0 : val
    this.next = next === undefined ? null : next
  }
  let oldListNode = null
  for (let index = arr.length - 1; index > -1; index--) {
    const val = arr[index]
    const newListNode = new ListNode(val, oldListNode)
    oldListNode = newListNode
  }
  return oldListNode
}
console.log(mergeKLists([createListNode([1, 4, 5]), createListNode([1, 3, 4]), createListNode([2, 6])]))
